package cmd

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"

	"github.com/eiannone/keyboard"
	"github.com/golang-module/carbon"
	"github.com/spf13/cobra"
)

func init() {
	rootCmd.AddCommand(aiCmd)
}

var aiCmd = &cobra.Command{
	Use:   "ai",
	Short: "ai",
	Run: func(cmd *cobra.Command, Args []string) {
		for _, word := range Args {
			// 当前时间
			if strings.Contains(word, "now") || strings.Contains(word, "当前时间") || strings.Contains(word, "现在几点") {
				timeNow := carbon.Now().ToDateTimeString()
				fmt.Printf("\r\n")
				fmt.Println("time now is:", timeNow)
			}
			// 递增版本号
			if word == "tag" {
				f, err := os.OpenFile("./internal/define/version.go", os.O_RDWR, 0666)
				if err != nil {
					log.Fatal(err)
				}
				defer f.Close()

				r := bufio.NewReader(f)
				pos := int64(0)
				for {
					line, err := r.ReadString('\n')
					if err == io.EOF {
						break
					}
					if err != nil {
						log.Fatal(err)
					}
					if strings.Contains(line, "APPVersion") {
						appVersion, _ := strconv.Atoi(strings.TrimRight(strings.Split(line, ".")[2], "\"\r\n"))
						nextVersion := appVersion + 1
						line = strings.TrimRight(line, strings.Split(line, ".")[2]) + strconv.Itoa(nextVersion) + "\""
						fmt.Printf("\r\n")
						fmt.Println(line)
						bytes := []byte(line)
						f.WriteAt(bytes, pos)
					}
					// 每一行读取完后记录位置
					pos += int64(len(line))
				}
			}
			// 开始交互，监听键盘
			if word == "start" {
				keysEvents, err := keyboard.GetKeys(10)

				if err != nil {
					panic(err)
				}
				defer func() {
					_ = keyboard.Close()
				}()

				fmt.Println("Press ESC to quit!")
				fmt.Print("chat:")

				var str string
				var CommandSlice []string
				commandIndex := 0

				regRes, _ := regexp.Compile("^[0-9a-zA-Z\u4e00-\u9fa5]$")
				for {
					event := <-keysEvents
					if event.Err != nil {
						panic(event.Err)
					}
					if regRes.MatchString(string(event.Rune)) {
						fmt.Print(string(event.Rune))
						str = str + string(event.Rune)
					} else if event.Key == keyboard.KeyEnter {
						if str != "" {
							saveCommand(str, &CommandSlice)
							commandIndex = len(CommandSlice)
						}
						str = ""
						fmt.Printf("\r\n")
						fmt.Print("chat:")
					}

					if event.Key == keyboard.KeyArrowUp {
						command := getCommand(&commandIndex, CommandSlice, !true)
						fmt.Print("\033[2K\r", "chat:", command)
					}
					if event.Key == keyboard.KeyArrowDown {
						command := getCommand(&commandIndex, CommandSlice, !false)
						fmt.Print("\033[2K\r", "chat:", command)
					}

					if event.Key == keyboard.KeyEsc {
						break
					}
				}
			}
		}
	},
}

// 保存输入命令
func saveCommand(str string, commandSlice *[]string) {
	*commandSlice = append(*commandSlice, str)
	if len(*commandSlice) > 10 {
		*commandSlice = (*commandSlice)[1:]
	}
}

// 提取输入命令
func getCommand(commandIndex *int, commandSlice []string, true bool) (commamd string) {
	if true {
		if *commandIndex > 0 {
			*commandIndex--
		}
	} else {
		if *commandIndex < len(commandSlice) {
			*commandIndex++
		}
	}
	if *commandIndex < len(commandSlice) {
		return commandSlice[*commandIndex]
	} else {
		return ""
	}
}
